package org.rqb.service;

import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.rqb.utils.HttpUtil;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Slf4j
public class SearchPointService {
    private String pointUrlPath1 = "https://github.com/mfuu/v2ray/blob/master/v2ray";

    private String pointUrlPath2 = "https://github.com/barry-far/V2ray-Configs/blob/main/Sub8.txt";

    public String searchPoints() {
        StringBuilder result = new StringBuilder();

        String html = HttpUtil.sendGet(pointUrlPath1);
        Document doc = Jsoup.parse(html);
        Element textarea = doc.getElementById("LC1");
        if (textarea != null) {
            String value = textarea.text();
            String s = new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8);
            result.append(s);
        }

        String html2 = HttpUtil.sendGet(pointUrlPath2);
        Document doc2 = Jsoup.parse(html2);
        Elements lines = doc2.select("div[id^=LC]");
        for (Element line : lines) {
            String pointStr = line.text();
            if (filterPointStr(pointStr)) {
                result.append(pointStr + "\n");
            }

        }
        return result.toString();
    }

    /**
     * 判断当前节点字符串是否包含trojan，vless，vmess，shadowsocks 等协议
     * @param pointStr
     * @return
     */
    private boolean filterPointStr(String pointStr) {
        if (pointStr.isEmpty()) {
            return false;
        }

        String lowerCase = pointStr.toLowerCase();
        if (lowerCase.contains("shadowsocks") || lowerCase.contains("ss")) {
            return true;
        } else if (lowerCase.contains("vless")) {
            return true;
        }else if (lowerCase.contains("vmess")){
            return true;
        } else if (lowerCase.contains("trojan")) {
            return true;
        }

        return false;
    }

}
